package com.example.demo.common.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * @Author: ak
 * @Date: 2020/4/10 10:16
 */
@Configuration
@Slf4j
public class KeyGeneratorConfig {
    @Bean
    public KeyGenerator bestKey() {
        return (target, method, params) -> {
            String sb = target.getClass().getName() +
                    "." + method.getName();
            if (params == null || params.length == 0 || params[0] == null) {
                return sb;
            }
            String join = Arrays.stream(params).map(Object::toString).collect(Collectors.joining("&"));
            String format = String.format("%s{%s}", sb, join);
            log.info("访问缓存，key：" + format);
            return format;
        };
    }

    @Bean
    public KeyGenerator questionKey() {
        return (target, method, params) -> {
            String sb = null;
            try {
                if (params == null || params.length == 0 || params[0] == null) {
                    return null;
                }
                Field questionId = target.getClass().getDeclaredField("questionId");
                questionId.setAccessible(true);
                Object questionIdKey = questionId.get(target);
                sb = target.getClass().getName() +
                        "." + questionIdKey.toString();
                log.info("访问缓存，key：" + sb);
            } catch (NoSuchFieldException | IllegalAccessException e) {
                log.error("创建key失败");
            }
            return sb;
        };
    }
}
